/**
 * 路由鉴权
 */
import {
	getCookieValue
} from '~/util/index.js';
import aes from '~/util/aes.js'

export default function({
	route,
	req,
	res,
	redirect,
	app
}) {
	let isServer = process.server;
	let isClient = process.client;
	let redirectURL = '/admin/login';//默认跳转到后台管理的登录页
	let token, path, path2; //path是路由地址，path2是路由地址加query的全路径
	//在服务器端
	if (isServer) {
		let cookies = req.headers.cookie;
		token = getCookieValue('token', cookies);
		path = req.url.split('?')[0];
		path2 = req.originalUrl; //req.originalUrl是全路径，带query
	}
	//在客户端
	if (isClient) {
		token = app.$cookies.get('token');
		path = route.path;
		path2 = route.fullPath;
	}
	/**
	 * TODO：①一级鉴权：判断是否已登录
	 * TIPS：采用白名单策略（不在数组中即需要验证是否登录，没登录跳转到登录页）
	 * 判断路由得判断不带query的那一部分路径(例如/index，即上述的path)，跳转到登录页时得告诉登录页跳转过来的路由全路径(例如/index?a=1，即上述的path2)
	 * ADDITIONAL:登录，注册的路由是判断是否登录时最起码要过滤的路由页面。
	 */
	let routeArr = [
		"/",
		"/payment",
		'/payment/payForm',
		'/payment/shopping',
		"/user/apply",
		"/login",
		"/register",
		"/admin/login",
		"/admin/register",
		"/admin/prelogin",
		"/admin/agentCenter",
		"/ieTips",
		"/order/login",
		"/preRegister",
		"/agentImprove",
		"/userRegister",
		"/agentRegister",
		"/forgotPassword",
		'/companyLogin'
	];
	//1.前台管理和后台管理的登录判断（前台管理和后台管理）
	if (routeArr.indexOf(path) == -1) {
		if (!token) {
			//如果路径是前台管理的路由之一
			let userRouteArr = [
				"/user",
				"/user/home",
				'/user/rank',
				"/user/home/menu",
				'/user/news/notice',
				'/user/myPurse',
				'/user/news/caseExchange',
				'/user/myApply/patent',
				'/user/myApply/software',
				'/user/myPay/payInquiry',
				'/user/myPay/invoiceQuery',
				'/user/myPay/invoiced',
				'/user/myFiles/fileDownload',
				'/user/home/feedBack',,
				'/user/home/recommend',
				'/user/home/editPhone',
				'/user/home/editPassword',
				'/user/home/editInformation',
				"/user/myOrder",
				"/user/myNews",
				"/user/invoices",
				'/user/invoice/canBeInvoice',
				'/user/invoice/alreadyInvoice',
				"/user/resetPw",
				"/user/updatePwd",
				"/user/updateTel",
				"/user/verifyPhone",
				"/user/userData",
				"/user/myOrder/patent",
				'/user/myOrder/orderInProcess',
				'/user/myOrder/dismantle',
				'/user/myOrder/codeList',
				'/user/personalCenter/myPurse',
				'/user/personalCenter/dstribution',
				'/user/myVIP'
			];
			if(userRouteArr.indexOf(path) >= 0){
				redirectURL = '/'//跳转到前台管理的登录页面
			}
			//跳到登录页
			redirect(redirectURL + '?from=' + path2)
		} else {
			/**
			 * TODO：②二级鉴权：判断是否有权限访问此路由（前台管理和后台管理）
			 * TIPS：根据用户的角色判断，用户的所有信息和登录凭证（token）一样，也存储在cookie中
			 * 没有权限访问此路由时跳转到首页
			 */
			let user = isServer?getCookieValue('user', req.headers.cookie):app.$cookies.get('user');
			if (user) {
				user =JSON.parse(aes.Decrypt(user));
				if(isNull(user.role_id)){
					if (path.indexOf('agentImprove') > -1 ) {
						return
					} else {
						//user信息异常
						redirect('/')
					}
				}else{
					/**
					 * 前台管理的路由只有普通用户（role_id为5）才能进，后台管理的路由反之。
					 * 2种用户账户不可僭越访问所述前台/后台管理的路由
					 */
					let routeArr3 = [
						"/user",
						"/user/home",
						'/user/rank',
						"/user/home/menu",
						'/user/myPurse',
						'/user/news/notice',
						'/user/news/caseExchange',
						'/user/myApply/patent',
						'/user/myApply/software',
						'/user/myPay/payInquiry',
						'/user/myPay/invoiced',
						'/user/myPay/invoiceQuery',
						'/user/myFiles/fileDownload',
						'/user/home/recommend',
						'/user/home/editPhone',
						'/user/home/editPassword',
						'/user/home/editInformation',
						'/user/home/feedBack',
						"/user/invoices",
						'/user/invoice/canBeInvoice',
						'/user/invoice/alreadyInvoice',
						"/user/myOrder",
						"/user/myNews",
						"/user/set/resetPw",
						"/user/set/updatePwd",
						"/user/set/updateTel",
						"/user/set/userData",
						"/user/set/verifyPhone",
						"/user/myOrder/patent",
						'/user/myOrder/orderInProcess',
						'/user/myOrder/dismantle',
						'/user/myOrder/codeList',
						'/user/personalCenter/myPurse',
						'/user/personalCenter/dstribution',
						'/user/myVIP'
					]
					//前台管理权限判断
					if(user.role_id==5){
						if(routeArr3.indexOf(path) == -1){//不存在，即不属于此路由数组
							redirectURL = '/admin/login'
							//跳到登录页
							redirect(redirectURL + '?from=' + path2)
						}
					//后台管理权限判断
					}else{
						if(routeArr3.indexOf(path) >0){
							redirectURL = '/'
							//跳到登录页
							redirect(redirectURL + '?from=' + path2)
						}
					}
				}
			}else{
				//user信息丢失
				redirect('/')
			}
		}
	//2.否则就是预注册管理的登录判断（预注册管理）
	}else{
		let agent = isServer?getCookieValue('agent', req.headers.cookie):app.$cookies.get('agent');
		let routeArr2 = ["/admin/agentCenter"];
		if (routeArr2.indexOf(path) >= 0) {
			if (!agent) {
				//跳到登录页
				// redirectURL = '/admin/prelogin';
				redirectURL = '/login?type=1';
				redirect(redirectURL + '?from=' + path2)
			}
		}
	}
}

function isNull(value){
	if(value === null || value === '' || value === undefined){
		return true;
	}else{
		return false
	}
}
